from rest_framework import serializers
from .models import NeedAuthenticatedSchoolMateProfile, AuthenticationStatus, SchoolMateProfile

from django.contrib.auth import get_user_model

User = get_user_model()  # 获取用户模型

from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
from django.db.models import Max

class UserSerializer(serializers.ModelSerializer):
    id = serializers.IntegerField(read_only=True, help_text='用户id')
    username = serializers.CharField(help_text="用户名")

    class Meta:
        model = User
        fields = ('id', 'username')


class NeedAuthenticatedSchoolMateProfileSerializer(serializers.ModelSerializer):
    user = UserSerializer(read_only=True, help_text='提交验证文档的人')
    mobile = serializers.CharField(help_text='电话号码', required=False)
    attendance_date = serializers.DateField(help_text='入学时间(YYYY-MM-DD)')
    major = serializers.CharField(help_text='专业名称')
    class_name = serializers.CharField(help_text='班级名称')
    student_id = serializers.CharField(help_text='学号')
    institute_name = serializers.CharField(help_text='学院名称')
    authentication_status = serializers.IntegerField(read_only=True, help_text='状态', source='get_status_display',
                                                     default=1)
    create_date = serializers.DateTimeField(help_text='创建日期', read_only=True)

    class Meta:
        model = NeedAuthenticatedSchoolMateProfile
        fields = '__all__'





class MyTokenObtainPairSerializer(TokenObtainPairSerializer):
    profile = NeedAuthenticatedSchoolMateProfileSerializer

    @classmethod
    def get_token(cls, user):
        token = super(MyTokenObtainPairSerializer, cls).get_token(user)
        # 添加额外信息
        token['username'] = user.username
        token['id'] = user.id
        # 存入个人信息中的是否认证成功字段
        token['authentication_status'] = user.profile.get_authentication_status_display()
        token['profile_id'] = user.profile.id

        # commit_profile_profile = user.commit_profile.aggregate(Max('id'))
        # commit_profile = NeedAuthenticatedSchoolMateProfile.objects.
        # commit_profile_serializer = NeedAuthenticatedSchoolMateProfileSerializer(commit_profile)
        # token['profile_id'] = commit_profile_profile.get('id__max')
        return token

    def validate(self, attrs):
        data = super().validate(attrs)

        refresh = self.get_token(self.user)

        # data['refresh'] = str(refresh)
        # data['access'] = str(refresh.access_token)
        data.pop('refresh')
        data['username'] = refresh['username']
        data['id'] = refresh['id']
        data['authentication_status'] = refresh['authentication_status']
        data['profile_id'] = refresh['profile_id']
        return data
